<template>
  <div class="prot-context" v-if="prots">
    <div class="header">
      <div class="back-botto" @click="goback"><img src="@/assets/images/community/back.png" alt="back"></div>
      <div class="creator-pic"><img :src="prots.creatorPic" alt="作者头像" class="creatorpic"></div> 
      <div class="creator-name">{{ prots.creatorNickname }}</div>
      <div class="share-btn" @click="showShare = true"><img src="@/assets/images/community/share.png" alt="share"></div>
    </div>
    <van-share-sheet
      v-model:show="showShare"
      title="立即分享给好友"
      :options="options"
      @select="onSelect"
     />
    <div class="Carousel">
      <van-swipe class="my-swipe"  indicator-color="white" lazy-render>
        <van-swipe-item v-for="image in prots.imageUrls" :key="image">
          <img :src="image" />
        </van-swipe-item>
      </van-swipe>
    </div>
    <div class="content">
      <div class="title">
        <h2>{{ prots.title }}</h2>
      </div>
      <div class="content-text" v-html="prots.content"></div>
      <div class="publish-time">{{ prots.createdAt }}</div>
      <van-divider />
      
      <!-- 评论区域 -->
      <div class="comments-section" v-if="mockData">
        <div class="comments-header">
          <span class="comments-count">共{{totalcount}}条评论</span>
        </div>
        
        <div class="comments-list">
          <div v-for="comment in mockData" :key="comment.commentId" class="comment-item">
            <div class="comment-user">
              <img :src="comment.userPic" :alt="comment.userNickname" class="user-avatar">
              <div class="user-info">
                <span class="user-name">{{ comment.userNickname }}</span>
                <span class="comment-time">{{ comment.createdAt }}</span>
              </div>
            </div>
            <div class="comment-content">{{ comment.content }}</div>
            
            <!-- 回复按钮 -->
            <div class="comment-actions">
              <span class="reply-btn" @click="showReplyInput(comment)">回复</span>
            </div>
            
            <!-- 回复输入框 -->
            <div class="reply-input" v-if="comment.showReply">
              <input 
                type="text" 
                v-model="comment.replyText"
                :placeholder="'回复 ' + comment.userNickname"
                @keyup.enter="submitReply(comment)"
              >
              <div class="reply-actions">
                <van-button size="small" @click="cancelReply(comment)">取消</van-button>
                <van-button size="small" type="primary" @click="submitReply(comment)">回复</van-button>
              </div>
            </div>
            
            <!-- 回复列表 -->
            <div class="reply-list" v-if="comment.replies && comment.replies.length > 0">
              <div v-if="!comment.expanded" class="replies-header" @click="toggleExpand(comment)">
                <span class="expand-icon">查看{{ comment.replies.length }}条回复 <van-icon name="arrow-down" /></span>
              </div>
              <div v-if="comment.expanded" class="replies-content">
                <div v-for="reply in comment.replies" :key="reply.commentId" class="reply-item">
                  <div class="reply-user">
                    <img :src="reply.userPic" :alt="reply.userNickname" class="user-avatar">
                    <div class="user-info">
                      <span class="user-name">{{ reply.userNickname }}</span>
                      <template v-if="reply.replyToUser">
                        <span class="reply-to">回复</span>
                        <span class="reply-name">{{ reply.replyToUser }}</span>
                      </template>
                      <span class="comment-time">{{ reply.createdAt }}</span>
                    </div>
                  </div>
                  <div class="reply-content">{{ reply.content }}</div>
                  
                  <!-- 回复按钮 -->
                  <div class="comment-actions">
                    <span class="reply-btn" @click="showReplyInput(reply)">回复</span>
                  </div>
                  
                  <!-- 回复输入框 -->
                  <div class="reply-input" v-if="reply.showReply">
                    <input 
                      type="text" 
                      v-model="reply.replyText"
                      :placeholder="'回复 ' + reply.userNickname"
                      @keyup.enter="submitReply(reply, comment.commentId)"
                    >
                    <div class="reply-actions">
                      <van-button size="small" @click="cancelReply(reply)">取消</van-button>
                      <van-button size="small" type="primary" @click="submitReply(reply, comment.commentId)">回复</van-button>
                    </div>
                  </div>
                </div>
                <!-- 收起回复按钮移到这里 -->
                <div class="replies-header collapse-header" @click="toggleExpand(comment)">
                  <span class="expand-icon">收起回复 <van-icon name="arrow-up" /></span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="bottom">
      <div class="comments">
        <input 
          type="text" 
          class="comments-text" 
          v-model="commentText"
          placeholder="说点什么..."
        >
      </div>
      <div class="botton-fa">
        <van-button round type="primary" @click="submitComment">发表评论</van-button>
      </div>
      <div class="collection">
        <van-icon name="like" :color="isRed ? 'red' : '#f0f0f0'" @click="toggleLike" class="collection-icon" size="40"/>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRouter,useRoute} from 'vue-router'
import { ref, computed, onMounted } from 'vue'
import { showToast } from 'vant';
import { getTweetDetail,getTweetComments,postComment,likeTweet,isLikeTweet  } from '../api';

import { useUserStore } from '@/stores/user';
const userStore = useUserStore();
const mockData=ref(null);
const route = useRoute();
const router = useRouter()
const showShare = ref(false);
const prots = ref(null);
let totalcount = 0;

const options = [
  { name: '微信', icon: 'wechat' },
  { name: '微博', icon: 'weibo' },
  { name: '复制链接', icon: 'link' },
  { name: '分享海报', icon: 'poster' },   
];    

const isRed = ref(false);
const toggleLike = async () => {  
    // 未登录提示登录  
    if (!userStore.token) {  
        showToast('请先登录');  
        return;  
    }  

    try {  
        const postId = route.params.id;  
        const res = await likeTweet(postId);  
        if (res.data.code === 200) {  
            // 切换收藏状态  
            isRed.value = !isRed.value;  
            // 根据当前收藏状态显示提示  
            showToast(isRed.value ? '点赞成功' : '取消点赞');  
        } else {  
            showToast(res.data.message || '操作失败');  
        }  
    } catch (error) {  
        console.error('收藏/取消收藏失败：', error);  
        showToast('操作失败');  
    }  
}; 
//检查点赞状态
const checktoggleLikeStatus = async () => {  
    // 未登录不检查收藏状态  
    if (!userStore.token) return;  

    try {  
        const postId = route.params.id;  
        const res = await isLikeTweet(postId);  

        // 根据后端返回的布尔值设置收藏状态  
        if (res.data.code === 200) {  
          isRed.value = res.data.data;  
        }  
    } catch (error) {  
        console.error('检查收藏状态失败：', error);  
    }  
};  
const onSelect = (option) => {
    // 未登录提示登录  
    if (!userStore.token) {  
        showToast('请先登录');  
        return;  
    } 
    showToast(option.name);
    showShare.value = false;


};
const goback = () => {
  router.go(-1)
}

// 在script部分修改处理评论嵌套结构的函数
const processComments = (comments) => {
  if (!comments || comments.length === 0) return [];
  
  // 创建评论映射和顶级评论数组
  const commentMap = {};
  const topLevelComments = [];
  
  // 首先将所有评论放入映射
  comments.forEach(comment => {
    // 处理时间格式
    comment.createdAt = formatTime(comment.createdAt);
    // 添加回复相关属性
    comment.showReply = false;
    comment.replyText = '';
    comment.replies = [];
    // 设置默认展开/收起状态
    comment.expanded = false; // 默认展开
    // 存入映射
    commentMap[comment.commentId] = comment;
  });
  
  // 然后为所有评论找到正确的replyToUser
  comments.forEach(comment => {
    if (comment.parentCommentId) {
      // 为每个评论设置直接回复的用户昵称
      comment.replyToUser = comment.parentUserNickname;
    }
  });
  
  // 最后组织成嵌套结构，所有回复放在一级评论下
  comments.forEach(comment => {
    if (comment.parentCommentId === null) {
      // 没有父评论，作为顶级评论
      topLevelComments.push(comment);
    } else {
      // 找到这个评论的根评论
      let currentParentId = comment.parentCommentId;
      let rootComment = commentMap[currentParentId];
      
      // 循环查找根评论
      while (rootComment && rootComment.parentCommentId !== null) {
        currentParentId = rootComment.parentCommentId;
        rootComment = commentMap[currentParentId];
      }
      
      // 如果找到了根评论，将回复添加到根评论的replies数组
      if (rootComment) {
        rootComment.replies.push(comment);
      } else {
        // 如果没有找到根评论，就直接添加到顶级评论列表
        topLevelComments.push(comment);
      }
    }
  });
  
  // 对每个顶级评论的replies按时间排序
  topLevelComments.forEach(comment => {
    if (comment.replies && comment.replies.length > 0) {
      comment.replies.sort((a, b) => {
        return new Date(a.createdAt) - new Date(b.createdAt);
      });
    }
  });
  
  return topLevelComments;
};

// 在getprotComments函数中，修改评论数据处理部分
const getprotComments = async() => {
  try{
    const protId=route.params.id;
    const res=await getTweetComments(protId);

    if(res.data.code===200){
      let comments=res.data.data;
      totalcount=comments.length;
      // 处理评论数据，构建嵌套结构
      mockData.value = processComments(comments);

    }else{
      showToast('获取评论失败');
    }
  }catch(err){
    console.error('获取评论失败：', err);
    showToast('获取评论失败');
  }
}

// 添加评论回复相关函数
const showReplyInput = (comment) => {
  // 未登录提示登录  
  if (!userStore.token) {  
        showToast('请先登录');  
        return;  
    } 
  // 关闭所有其他回复框
  if (mockData.value) {
    mockData.value.forEach(c => {
      c.showReply = false;
      if (c.replies) {
        c.replies.forEach(r => r.showReply = false);
      }
    });
  }
  comment.showReply = true;
};

const cancelReply = (comment) => {
  comment.showReply = false;
  comment.replyText = '';
};

const submitReply = (comment, rootCommentId = null) => {
  if (!comment.replyText.trim()) {
    showToast('请输入回复内容');
    return;
  }
  const commentdata={
    postId:route.params.id,
    content: comment.replyText,
    parentCommentId: comment.commentId,
  }

  postComment(commentdata).then(res => {
    if (res.data.code === 200) {
      showToast('回复成功')
      comment.showReply = false;
      comment.replyText = '';
      // 刷新评论列表
      getprotComments();
    } else {
      showToast('回复失败')
    }
  })
  // // 这里应该调用后端API发表回复
  // // 如果提供了rootCommentId，说明这是一个回复中的回复，需要关联到根评论
  // console.log('回复评论:', comment.commentId, '根评论:', rootCommentId, '内容:', comment.replyText);
  // showToast('回复成功');
  // comment.showReply = false;
  // comment.replyText = '';
};

//获取推文详细信息
const getprotDetail = async() => {
  try{

    const protId=route.params.id;

    const res=await getTweetDetail(protId);
   
    if(res.data.code===200){
      prots.value=res.data.data;
    }else{
      showToast('获取推文失败');
    }
  }catch(err){
    console.error('获取文章详情失败：', err);
    showToast('获取推文失败');
  }
}


// 格式化时间的函数
const formatTime = (timeString) => {
  const date = new Date(timeString)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`}

// 计算属性：格式化后的发布时间
const formatPublishTime = computed(() => {
  return formatTime(mockData.publishTime)
})

// 评论输入框的值
const commentText = ref('')

// 发表评论
const submitComment = () => {
  // 未登录提示登录  
  if (!userStore.token) {  
        showToast('请先登录');  
        return;  
    } 
  if (!commentText.value.trim()) {
    showToast('请输入评论内容')
    return
  }
  const postdata={
    postId:route.params.id,
    content: commentText.value,
  }
  console.log('发表评论:', postdata);
  postComment(postdata).then(res => {
    if (res.data.code === 200) {
      showToast('评论成功')
      commentText.value = ''
      // 刷新评论列表
      getprotComments();
    } else {
      showToast('评论失败')
    }
  })
}

// 添加切换展开/收起的方法
const toggleExpand = (comment) => {
  comment.expanded = !comment.expanded;
};

onMounted(() => {
  getprotDetail();
  getprotComments();
  checktoggleLikeStatus();
});
</script>

<style lang="scss" scoped>
.prot-context {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #fff;
  padding-bottom: 66px; // 为底部固定栏留出空间

  .header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    display: flex;
    align-items: center;
    padding: 12px 16px;
    background-color: #fff;
    height: 56px;
    border-bottom: 1px solid #eee;
    z-index: 100;

    .back-botto {
      width: 24px;
      height: 24px;
      img {
        width: 100%;
        height: 100%;
      }
    }

    .creator-pic {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      overflow: hidden;
      margin-left: 12px;
      
      .creatorpic {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .creator-name {
      margin-left: 8px;
      font-size: 15px;
      color: #333;
    }

    .share-btn {
      margin-left: auto;
      width: 24px;
      height: 24px;
      img {
        width: 100%;
        height: 100%;
      }
    }
  }

  .Carousel {
    margin-top: 56px;
    width: 100%;
    height: 300px;
    background-color: #f5f5f5;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .my-swipe {
      width: 100%;
      height: 100%;
      
      .van-swipe-item {
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f5f5;
        color: #999;
        font-size: 16px;
      }
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
  }

  .content {
    flex: 1;
    padding: 16px;
    background-color: #fff;
    margin-bottom: 50px; // 为底部栏留出空间
    overflow-y: auto; // 添加垂直滚动
    -webkit-overflow-scrolling: touch; // 优化移动端滚动体验
    height: calc(100vh - 406px); // 计算内容区域高度（视口高度减去头部56px、轮播图300px和底部50px）

    .title {
      margin-bottom: 12px;
      h2 {
        font-size: 20px;
        font-weight: 900;
        color: #333;
      }
    }

    .content-text {
      font-size: 14px;
      line-height: 1.6;
      color: #666;
      margin-bottom: 16px;
      white-space: pre-wrap;
      word-break: break-all;
    }

    .publish-time {
      font-size: 12px;
      color: #999;
      margin: 8px 0 16px;
      padding-left: 2px;
    }

    .comments-section {
      margin-top: 16px;

      .comments-header {
        margin-bottom: 16px;
        
        .comments-count {
          font-size: 14px;
          color: #666;
          font-weight: 500;
        }
      }

      .comments-list {
        .comment-item {
          margin-bottom: 16px;
          padding-bottom: 16px;
          border-bottom: 1px solid #f5f5f5;

          &:last-child {
            margin-bottom: 0;
            padding-bottom: 0;
            border-bottom: none;
          }

          .comment-user {
            display: flex;
            align-items: center;
            margin-bottom: 8px;

            .user-avatar {
              width: 32px;
              height: 32px;
              border-radius: 50%;
              margin-right: 8px;
              object-fit: cover;
            }

            .user-info {
              flex: 1;
              display: flex;
              align-items: center;
              flex-wrap: wrap;
              gap: 4px;
              
              .user-name {
                font-size: 14px;
                color: #333;
                font-weight: 500;
              }

              .comment-time {
                font-size: 12px;
                color: #999;
              }
            }
          }

          .comment-content {
            font-size: 14px;
            color: #666;
            line-height: 1.5;
            margin-left: 40px;
          }
        }
      }
    }
  }

  .bottom {
    position: fixed;
    height: 50px;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 8px 16px;
    background-color: #fff;
    border-top: 1px solid #eee;
    display: flex;
    align-items: center;
    z-index: 100;

    .comments {
      flex: 1;
      margin-right: 12px;
      
      .comments-text {
        width: 100%;
        height: 36px;
        padding: 0 16px;
        border: 1px solid #eee;
        border-radius: 18px;
        background-color: #f9f9f9;
        font-size: 14px;
        color: #333;
        
        &::placeholder {
          color: #999;
        }
        
        &:focus {
          outline: none;
          border-color: #ddd;
          background-color: #fff;
        }
      }
    }

    .botton-fa {
      margin-right: 12px;
      
      .van-button {
        height: 36px;
        padding: 0 20px;
        font-size: 14px;
        background: #4b6bfb;
        
        &:active {
          opacity: 0.9;
        }
      }
    }

    .collection {
      .collection-icon {
        font-size: 24px;
        padding: 6px;
      }
    }
  }
}

.comment-actions {
  margin-left: 40px;
  margin-top: 4px;
  
  .reply-btn {
    font-size: 13px;
    color: #6495ed;
    cursor: pointer;
    
    &:hover {
      opacity: 0.8;
    }
  }
}

.reply-input {
  margin-left: 40px;
  margin-top: 8px;
  
  input {
    width: 100%;
    height: 36px;
    padding: 0 12px;
    border: 1px solid #eee;
    border-radius: 4px;
    background-color: #f9f9f9;
    font-size: 14px;
    
    &::placeholder {
      color: #999;
    }
    
    &:focus {
      outline: none;
      border-color: #4b6bfb;
    }
  }
  
  .reply-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 8px;
    gap: 8px;
  }
}

.reply-list {
  margin-left: 40px;
  margin-top: 12px;
  margin-bottom: 8px;
  background: #fefdfd;
  border-radius: 8px;
  padding: 0;
  overflow: hidden;

  .replies-header {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px 0;
    cursor: pointer;
    border-radius: 8px;
    background: #ffffff;
    transition: all 0.2s;
    
    &:hover {
      background: #f0f0f0;
    }
    
    .expand-icon {
      font-size: 13px;
      color: #6495ed;
      display: flex;
      align-items: center;
      font-weight: 500;
      
      .van-icon {
        margin-left: 4px;
        font-size: 12px;
      }
    }
  }
  
  .replies-content {
    background-color: #ffffff;
    max-height: 500px;
    overflow-y: auto;
    padding: 8px 12px;
  }

  .reply-item {
    background-color: #ffffff;
    margin-bottom: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.03);

    &:last-child {
      margin-bottom: 0;
      padding-bottom: 0;
      border-bottom: none;
    }

    .reply-user {
      display: flex;
      align-items: flex-start;
      margin-bottom: 4px;

      .user-avatar {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        margin-right: 8px;
      }

      .user-info {
        flex: 1;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 4px;
        
        .user-name {
          font-size: 13px;
          color: #333;
          font-weight: 500;
        }

        .reply-to {
          font-size: 12px;
          color: #6495ed;
          &:before {
            content: "・";
            margin-right: 4px;
          }
        }

        .reply-name {
          font-size: 13px;
          color: #6495ed;
          font-weight: 500;
        }

        .comment-time {
          font-size: 12px;
          color: #999;
          &:before {
            content: "・";
            margin-right: 4px;
          }
        }
      }
    }

    .reply-content {
      margin-left: 32px;
      font-size: 13px;
      color: #333;
      line-height: 1.5;
    }
    
    .comment-actions {
      margin-left: 32px;
      margin-top: 4px;
      
      .reply-btn {
        font-size: 12px;
        color: #6495ed;
      }
    }
  }

  .collapse-header {
    border-top: 1px solid rgba(0, 0, 0, 0.03);
    margin-top: 8px;
    padding: 12px 0;
  }
}
</style>
